<template>
    <div class="media-attr">
        <div class="size-change" v-show="currentElementList[0].component === 'Picture' && currentElementList[0].data.length === 1">
            <span @click="picture.setPictureSize(currentElementList[0], 'contain')" :class="{'active': currentElementList[0].style.objectFit === 'contain'}">自适应</span>
            <span @click="picture.setPictureSize(currentElementList[0], 'fill')" :class="{'active': currentElementList[0].style.objectFit === 'fill'}">充满</span>
            <span @click="picture.setPictureSize(currentElementList[0], 'reality')" :class="{'active': currentElementList[0].style.objectFit === 'reality'}">实际宽高</span>
        </div>
        <div class="thumd-wrap">
            <draggable v-model="currentElementPicList" class="thumb-list" @update="dragEndSort">
                <transition-group>
                    <div v-for="(item, index) in currentElementPicList" :key="index" class="single-thumb">
                        <div class="handle-wrap">
                            <i class="el-icon-edit" v-show="!item.id" @click="editCustom(item, index)"></i>
                            <i class="el-icon-delete" v-show="currentElementPicList.length > 1" @click="deleteLoop(item, index)"></i>
                        </div>
                        <img :src="item.id ? getPreview(item.preview) : item.preview" alt="" />
                    </div>
                </transition-group>
            </draggable>
            <div class="custom-resource" v-show="customVisible" :style="{position: customType === 'new' ? '' : 'absolute', top: editCustomIndex * 110 + 'px', left: '0', zIndex: 10}">
                <img :src="customUrl" class="custom-img" id="customPic" />
                <textarea :rows="5" placeholder="请输入自定义资源地址" :id="picture.getCustomPicName()"></textarea>
                <div class="button-wrap custom-button-wrap">
                    <el-button type="primary" @click="cancelCustomPic">取 消</el-button>
                    <el-button type="primary" @click="addCustomPic(customType)">添 加</el-button>
                </div>
            </div>
        </div>
        <div class="button-wrap">
            <el-button type="primary" @click="getPicList()">资源库</el-button>
            <FileUpload fileType="01" componentType="PicLoop" buttonStyle="button" />
            <el-button type="primary" @click="customUrlEvent">自定义</el-button>
        </div>

        <el-drawer v-if="repository" :visible.sync="repository" title="资源库" size="350px" @close="closePop">
            <div class="resource-wrap" :id="window.getRootName() + 'PICTURE'">
                <ul v-show="currentElementList[0].component === 'Picture'">
                    <li v-for="(item, index) in picList" :class="{ 'select-resource' : selectMediaIndex.indexOf(item.id) > -1 }" :key="'pic_' + index" @click="selectPicture(item, index)">
                        <img class="img-resource" :src="getImgUrl(item, index)" alt="" />
                    </li>
                </ul>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import FileUpload from '@/view/component/FileUpload.vue';
import store from '@/js/store/state.js';
import draggable from 'vuedraggable';
import config from '@/js/util/config.js';
import tree from '@/js/main/tree.js';
import template from '@/js/element/template.js';
import picture from '@/js/main/attribute/picture.js';
import history from '@/js/main/history.js';
import util from '@/js/util/util.js';
import JQuery from 'jquery';
import message from '@/js/util/message.js';
import loadingImg from '@/image/main/toolbar/toolbar_loading.svg';

export default {
    data() {
        return {
            currentElementPicList: [],
            currentElementList: store.getCurrentElementList(),
            repository: false,
            menuData: tree,
            picture: picture,
            picList: [],
            selectMediaIndex: [],
            customVisible: false,
            customType: 'new',
            editCustomIndex: -1,
            customUrl: '',
            showImgLineNum: 0,
            recorScrolldNum: 24,
            window: window,
            defaultImg: 'src/image/main/toolbar/toolbar_loading.svg'
        };
    },
    mounted() {
        let data = util.clone(this.currentElementList[0].data);
        for (let i = 0; i < data.length; i++) {
            this.currentElementPicList.splice(i, 0, data[i]);
        }
        this.setSelectIndex(this.currentElementList);
    },
    watch: {
        currentElementList: {
            handler() {
                let data = util.clone(this.currentElementList[0].data);
                this.currentElementPicList = data;
                this.setSelectIndex(this.currentElementList);
            },
            deep: true
        }
    },
    methods: {
        getImgUrl(row, index) {
            if (index <= this.recorScrolldNum) {
                return row.icon;
            } else {
                return loadingImg;
            }
        },
        customUrlEvent() {
            this.customVisible = true;
            this.customType = 'new';
            this.clearCustomUrl();
        },
        clearCustomUrl() {
            JQuery('#' + picture.getCustomPicName()).val('');
        },
        editCustom(item, index) {
            this.customVisible = true;
            this.customType = 'edit';
            this.editCustomIndex = index;
            JQuery('#' + picture.getCustomPicName()).val(item.url);
        },
        cancelCustomPic() {
            this.clearCustomUrl();
            this.customVisible = false;
        },
        imgLoad(url, callback) {
            let img = new Image();
            img.src = url;
            if (img.complete) {
                callback(img.width, img.height);
            } else {
                img.onload = function() {
                    callback(img.width, img.height);
                    img.onload = null;
                };
            }
        },
        addCustomPic(type) {
            let _this = this;
            let url = JQuery('#' + picture.getCustomPicName())
                .val()
                .replace(/\s*/g, '');
            if (url.length > 0) {
                this.customVisible = false;
                this.imgLoad(url, function(width, height) {
                    let customPic = {
                        height: height,
                        width: width,
                        preview: url,
                        url: url
                    };
                    if (type === 'new') {
                        _this.currentElementList[0].data.splice(_this.currentElementList[0].data.length, 0, customPic);
                        history.addHistory(store.clone(), 42);
                    } else {
                        _this.currentElementList[0].data.splice(_this.editCustomIndex, 1);
                        _this.currentElementList[0].data.splice(_this.editCustomIndex, 0, customPic);
                        history.addHistory(store.clone(), 44);
                    }
                    _this.clearCustomUrl();
                });
            } else {
                message.message('请输入正确的资源地址！', 'warning');
            }
        },
        setSelectIndex(elementList) {
            this.selectMediaIndex = [];
            for (let i = 0; i < elementList[0].data.length; i++) {
                if (elementList[0].component === 'Picture') {
                    this.selectMediaIndex.splice(this.selectMediaIndex.length, 0, elementList[0].data[i].id);
                }
            }
        },
        dragEndSort(event) {
            let from = event.oldIndex;
            let to = event.newIndex;
            if (from >= 0 && from < this.currentElementList[0].data.length && to >= 0 && to < this.currentElementList[0].data.length && from != to) {
                let element = this.currentElementList[0].data[from];
                this.currentElementList[0].data.splice(from, 1);
                this.currentElementList[0].data.splice(to, 0, element);
            }
            history.addHistory(store.clone(), 41);
        },
        deleteLoop(item, index) {
            let selectPicElement = template.baseElementMap[item.id];
            let arrIndex = this.selectMediaIndex.indexOf(item.id);
            let deleteIndex = -1;
            let curElementListLen = this.currentElementList[0].data.length;
            if (!item.id) {
                deleteIndex = index;
            } else {
                for (let i = 0; i < this.currentElementList[0].data.length; i++) {
                    if (this.currentElementList[0].data[i].id === selectPicElement.data[0].id) {
                        deleteIndex = i;
                    }
                }
            }
            if (curElementListLen > 1) {
                this.selectMediaIndex.splice(arrIndex, 1);
                this.currentElementList[0].data.splice(deleteIndex, 1);
            }
            history.addHistory(store.clone(), 43);
        },
        selectPicture(item) {
            let selectPicElement = template.baseElementMap[item.id];
            let arrIndex = this.selectMediaIndex.indexOf(item.id);
            let deleteIndex = -1;
            let curElementListLen = this.currentElementList[0].data.length;
            for (let i = 0; i < this.currentElementList[0].data.length; i++) {
                if (this.currentElementList[0].data[i].id === selectPicElement.data[0].id) {
                    deleteIndex = i;
                }
            }
            if (arrIndex > -1) {
                if (curElementListLen > 1) {
                    this.selectMediaIndex.splice(arrIndex, 1);
                    this.currentElementList[0].data.splice(deleteIndex, 1);
                }
            } else {
                this.selectMediaIndex.splice(this.selectMediaIndex.length, 0, item.id);
                this.currentElementList[0].data.splice(this.currentElementList[0].data.length, 0, util.clone(selectPicElement.data[0]));
            }
            history.addHistory(store.clone(), 45);
        },
        getPreview(url) {
            return url ? `${config.getServiceURL('scene')}service/scene/file/download?file=${url}` : `src/image/main/toolbar/logo.svg`;
        },
        getPicList() {
            let _this = this;
            this.repository = true;
            let resourcesNum = this.menuData[3].children[0].children.length;
            this.$nextTick(() => {
                let dom = document.getElementById(`${window.getRootName()}PICTURE`);
                this.picList = this.menuData[3].children[0].children;
                this.recorScrolldNum = Math.ceil(dom.clientHeight / 90) * 2 + 6;
                this.scrollListener();
            });
        },
        scrollListener(type = true) {
            let _this = this;
            let dom = document.getElementById(`${window.getRootName()}PICTURE`);
            if (type) {
                dom.addEventListener('scroll', _this.elementScroll);
            } else {
                dom.removeEventListener('scroll', _this.elementScroll);
            }
        },
        elementScroll: util.debounce(function($event) {
            let height = Math.ceil(($event.target.scrollTop + $event.target.clientHeight) / 90);
            if (this.recorScrolldNum > height * 2) return;
            this.recorScrolldNum = height * 2;
        }),
        closePop() {
            let _this = this;
            this.recorScrolldNum = 24;
            this.scrollListener(false);
        }
    },
    components: {
        FileUpload,
        draggable
    }
};
</script>

<style scoped lang="scss">
$BtnBackCol: #ffffff0f;
$BtnHoverBackCol: #ffffff33;
.size-change {
    display: flex;
    align-items: center;
    border-radius: 5px;
    margin: 10px;
    span {
        padding: 5px 0;
        width: 33%;
        text-align: center;
        background: $BtnBackCol;
        color: $FontWhite;
        cursor: pointer;
        border-right: 1px solid $BorderColor;
    }
    span:hover,
    .active {
        background: $BtnHoverBackCol;
    }
    span:first-child {
        border-radius: 3px 0 0 3px;
    }
    span:last-child {
        border-radius: 0 3px 3px 0;
    }
}
.thumb-list {
    margin-top: 20px;
    width: 100%;
    .single-thumb {
        width: 100%;
        height: 100px;
        border: 1px solid $BtnHoverBackCol;
        border-radius: 3px;
        margin: 10px 0;
        position: relative;
        img {
            width: 100%;
            height: 100%;
            object-position: 50%;
            object-fit: contain;
        }
        .handle-wrap {
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 10;
            font-size: 18px;
            color: $FontWhite;
            cursor: pointer;
            i {
                margin: 0 5px;
            }
        }
    }
}
.button-wrap {
    margin-top: 10px;
    display: flex;
    align-items: center;
    text-align: center;
}
.button-wrap ::v-deep.el-button--primary {
    width: 75px;
    background: $BtnBackCol !important;
    height: 30px;
    border: none;
    line-height: 8px !important;
    margin: 0 0.1rem;
    &:hover {
        background: $BtnHoverBackCol !important;
    }
}
.media-attr ::v-deep.el-drawer {
    background: #212121ff;
}
.media-attr ::v-deep.el-drawer__header {
    margin-bottom: 0;
    color: $FontWhite;
}
.resource-wrap {
    // .resource-list {
    // overflow: auto;
    padding: 5px 15px;
    width: 100%;
    height: calc(100vh - 70px);
    overflow-y: auto;
    li {
        width: 45%;
        height: 80px;
        margin: 5px;
        float: left;
        text-align: center;
        vertical-align: middle;
        overflow: hidden;
        border: 1px solid #39435d;
        cursor: pointer;
        border-radius: 2px;
        position: relative;
        img {
            width: 100%;
            height: 100%;
            object-position: 50% 50%;
            object-fit: contain;
        }
    }
    .select-resource {
        border: 1px solid #f50;
    }
    // }
}
.custom-resource {
    height: 140px;
    width: 100%;
    background: #212121ff;
    .custom-img {
        height: 100px;
    }
    textarea {
        border: 1px solid $BorderColor;
        background: $BtnBackCol;
        padding: 10px 5px;
        color: $FontWhite;
        width: 100%;
        border-radius: 3px;
    }
    .custom-button-wrap {
        display: flex;
        justify-content: space-between;
    }
}
.thumd-wrap {
    position: relative;
}
</style>